<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yang-da-xiong.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="前言记录opencv关于求最大值、最小值和二值化的相关函数及操作">
<meta property="og:type" content="article">
<meta property="og:title" content="opencv学习笔记之图像最值与二值化">
<meta property="og:url" content="https://yang-da-xiong.gitee.io/2022/02/13/opencv%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%E4%B9%8B%E5%9B%BE%E5%83%8F%E6%9C%80%E5%80%BC%E4%B8%8E%E4%BA%8C%E5%80%BC%E5%8C%96/index.html">
<meta property="og:site_name" content="杨大熊的代码世界">
<meta property="og:description" content="前言记录opencv关于求最大值、最小值和二值化的相关函数及操作">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/81bb867221ee4082b81ad43bf740f178.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5p2o5aSn54aK55qE5Luj56CB5LiW55WM,size_15,color_FFFFFF,t_70,g_se,x_16">
<meta property="og:image" content="https://img-blog.csdnimg.cn/32acfdefbdc842e7b011b626d20d9727.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/568482d79b2542099d8257b3047791c9.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/d561bc8c8a2446c7a9c3a5213885f569.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/c5387486452b44168cbcec6e32f77209.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/02fb90b0437f4823a63377138bab8b9c.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/97e316a7fcbc4e21807102dca1b3bec1.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/be0f6d5fc9954132a650cfb55b91c03a.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/dd0a2f4d54694c14a1f8a14de69c066f.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/ec3c729497fe40e8b1b2bd3724c34a3f.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/c4177336af3f4f13b4fa6f835fd42ef1.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/044a064b0fff4dc8beba31a48c34a3b5.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/c5e772d0ab8e4fc098e0eb2c6521fbaa.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="article:published_time" content="2022-02-13T13:53:55.888Z">
<meta property="article:modified_time" content="2022-02-13T14:31:56.449Z">
<meta property="article:author" content="杨大熊">
<meta property="article:tag" content="c++">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/81bb867221ee4082b81ad43bf740f178.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5p2o5aSn54aK55qE5Luj56CB5LiW55WM,size_15,color_FFFFFF,t_70,g_se,x_16">

<link rel="canonical" href="https://yang-da-xiong.gitee.io/2022/02/13/opencv%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%E4%B9%8B%E5%9B%BE%E5%83%8F%E6%9C%80%E5%80%BC%E4%B8%8E%E4%BA%8C%E5%80%BC%E5%8C%96/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>opencv学习笔记之图像最值与二值化 | 杨大熊的代码世界</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">杨大熊的代码世界</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://yang-da-xiong.gitee.io/2022/02/13/opencv%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%E4%B9%8B%E5%9B%BE%E5%83%8F%E6%9C%80%E5%80%BC%E4%B8%8E%E4%BA%8C%E5%80%BC%E5%8C%96/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.png">
      <meta itemprop="name" content="杨大熊">
      <meta itemprop="description" content="各类IT知识分享">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="杨大熊的代码世界">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          opencv学习笔记之图像最值与二值化
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2022-02-13 21:53:55 / 修改时间：22:31:56" itemprop="dateCreated datePublished" datetime="2022-02-13T21:53:55+08:00">2022-02-13</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">算法</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>记录opencv关于求最大值、最小值和二值化的相关函数及操作</p>
<span id="more"></span>

<h1 id="一、图像最大值与最小值统计"><a href="#一、图像最大值与最小值统计" class="headerlink" title="一、图像最大值与最小值统计"></a>一、图像最大值与最小值统计</h1><p>minMaxLoc（）函数</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">void minMaxLoc(InputArray src, double * minVal, double * maxVal=0, Point * minLoc =0, Point * maxLoc=0, InputArray mask=noArray())</span><br></pre></td></tr></table></figure>

<p>src：需要操作的图像或矩阵，但必须是单通道矩阵</p>
<p>minVal：图像或者矩阵中的最小值</p>
<p>maxVal：图像或者矩阵中的最大值</p>
<p>minLoc：图像或者矩阵中的最小值在矩阵中的坐标</p>
<p>maxLoc：图像或者矩阵中的最大值在矩阵中的坐标</p>
<p>Point数据类型表示图像坐标，以矩阵左上角为坐标原点，水平方向为x轴，垂直方向为y轴，Point（x，y）表示图像的第x行第y列元素</p>
<p>注意minMaxLoc()函数输入参数一定要注意添加取地址符。</p>
<p>示例程序：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;opencv2\opencv.hpp&gt;</span>  <span class="comment">//加载OpenCV4的头文件</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;vector&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> cv; <span class="comment">//OpenCV命名空间</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	system(<span class="string">&quot;color F0&quot;</span>);  <span class="comment">//更改界面输出颜色</span></span><br><span class="line">	<span class="keyword">float</span> a[<span class="number">12</span>] = &#123; <span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">10</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>,<span class="number">0</span> &#125;;</span><br><span class="line">	Mat img = Mat(<span class="number">3</span>, <span class="number">4</span>, CV_32FC1, a);  <span class="comment">//单通道矩阵，3*4</span></span><br><span class="line">	Mat imgs = Mat(<span class="number">2</span>, <span class="number">3</span>, CV_32FC2, a);  <span class="comment">//多通道矩阵,2*3*2</span></span><br><span class="line">	<span class="keyword">double</span> minVal, maxVal;  <span class="comment">//用于存放矩阵中的最大值和最小值</span></span><br><span class="line">	Point minIdx, maxIdx;   <span class="comment">//用于存放矩阵中的最大值和最小值在矩阵中的位置</span></span><br><span class="line"></span><br><span class="line">	minMaxLoc(img, &amp;minVal, &amp;maxVal, &amp;minIdx, &amp;maxIdx);</span><br><span class="line">	<span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;img中最大值是：&quot;</span> &lt;&lt; maxVal &lt;&lt;<span class="string">&quot;		&quot;</span>&lt;&lt;<span class="string">&quot;在矩阵中的位置：&quot;</span>&lt;&lt;maxIdx&lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">	<span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;img中最小值是：&quot;</span> &lt;&lt; minVal &lt;&lt;<span class="string">&quot;		&quot;</span>&lt;&lt;<span class="string">&quot;在矩阵中的位置：&quot;</span>&lt;&lt;minIdx&lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">	</span><br><span class="line">	Mat imgs_re = imgs.reshape(<span class="number">1</span>, <span class="number">4</span>);  <span class="comment">//将多通道矩阵变成单通道矩阵</span></span><br><span class="line">	minMaxLoc(imgs_re, &amp;minVal, &amp;maxVal, &amp;minIdx, &amp;maxIdx);</span><br><span class="line">	<span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;img中最大值是：&quot;</span> &lt;&lt; maxVal &lt;&lt; <span class="string">&quot;		&quot;</span> &lt;&lt; <span class="string">&quot;在矩阵中的位置：&quot;</span> &lt;&lt; maxIdx &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">	<span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;img中最小值是：&quot;</span> &lt;&lt; minVal &lt;&lt; <span class="string">&quot;		&quot;</span> &lt;&lt; <span class="string">&quot;在矩阵中的位置：&quot;</span> &lt;&lt; minIdx &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;  <span class="comment">//程序结束</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="https://img-blog.csdnimg.cn/81bb867221ee4082b81ad43bf740f178.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5p2o5aSn54aK55qE5Luj56CB5LiW55WM,size_15,color_FFFFFF,t_70,g_se,x_16" alt="在这里插入图片描述"></p>
<h1 id="二、图像二值化"><a href="#二、图像二值化" class="headerlink" title="二、图像二值化"></a>二、图像二值化</h1><p>在图像中一般像素值为只有两种（最大值和最小值）的图像成为二值图像，二值图像色彩种类少，可以进行高度的压缩，节省存储空间，将非二值图像经过计算变成二值图像的过程称为图像的二值化。OpenCV提供了两种函数用于实现图像的二值化。</p>
<h4 id="threshold-函数"><a href="#threshold-函数" class="headerlink" title="threshold()函数"></a>threshold()函数</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">double threshlod(InputArray src, OutpurArray dst, double thresh, double maxval, int type)</span><br></pre></td></tr></table></figure>

<p>src：待二值化的图像，图像只能是CV_8U和CV_32F两种数据类型。对于图像通道数目的要求与选择的二值化方法相关。</p>
<p>dst：二值化后的图像，与输入图像具有相同的尺寸、数据类型和通道数</p>
<p>thresh：二值化的阈值</p>
<p>maxval：二值化过程的最大值，它只在THRESH_BINARY 和 THRESH_BINARY_INV两种二值化方法中使用</p>
<p>type：选择图像二值化方法的标志</p>
<p>二值化中type的取值表：</p>
<table>
<thead>
<tr>
<th>标志函数</th>
<th>简记</th>
<th>作用</th>
</tr>
</thead>
<tbody><tr>
<td>THRESH_BINARY</td>
<td>0</td>
<td>灰度值大于阈值的为最大值，其他值为0</td>
</tr>
<tr>
<td>THRESH_BINARY_INV</td>
<td>1</td>
<td>灰度值大于阈值的为0，其他值为最大值</td>
</tr>
<tr>
<td>THRESH_TRUNC</td>
<td>2</td>
<td>灰度值大于阈值的为阈值，其他值不变</td>
</tr>
<tr>
<td>THRESH_TOZERO</td>
<td>3</td>
<td>灰度值大于阈值的不变，其他值为0</td>
</tr>
<tr>
<td>THRESH_TOZERO_INV</td>
<td>4</td>
<td>灰度值大于阈值的为0，其他值不变</td>
</tr>
<tr>
<td>THRESH_OTSU</td>
<td>8</td>
<td>大律法自动寻求全局阈值</td>
</tr>
<tr>
<td>THRESH_TRIANGLE</td>
<td>16</td>
<td>三角形法自动寻求全局阈值</td>
</tr>
</tbody></table>
<p>特别要研究的THRESH_OTSU和THRESH_TRIANGLE函数，这两个函数可以与上面的5种一起使用，例如”THRESH_BINARY| THRESH_OTSU”。这两个函数相比于自己设置阈值的优势在于，它们是分别通过大律法和三角形法并结合图像的灰度值获取的二值化阈值，多数情况下比人为设定的阈值更加合理，从而使图像在处理后更加符合理想的状态，运用这两种方法设定的阈值会被自动传入到参数thresh中。</p>
<p>具体这两种方法推荐两篇博客：</p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/xiao_lxl/article/details/45577357">图像预处理——二值化(大律法)_xiao_lxl的专栏-CSDN博客_大律法二值化</a> </p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_34203832/article/details/89938504">图像处理之三角法图像二值化_weixin_34203832的博客-CSDN博客</a> </p>
<p>threshold（）全局只用一个阈值，而adaptiveThreshold（）函数提供了两种局部自适应阈值的二值化方法</p>
<h4 id="adaptiveThreshold-函数"><a href="#adaptiveThreshold-函数" class="headerlink" title="adaptiveThreshold()函数"></a>adaptiveThreshold()函数</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">void adaptiveThreshold(InputArray src, OutputArray dst, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C)</span><br></pre></td></tr></table></figure>

<p>src：待二值化的图像，图像只能是CV_8UC1数据类型</p>
<p>dst：二值化后的图像，与输入图像具有相同的尺寸、数据类型</p>
<p>maxValue：二值化的最大值</p>
<p>adaptiveMethod：自适应确定阈值的方法，分为均值法ADAPTIVE_THRESH_MEAN_C 和 高斯法 ADAPTIVE_THRESH_GAUSSIAN_C两种</p>
<p>thresholType：选择图像二值化方法的标志，只能是THRESH_BINARY 和 THRESH_BINARY_INV</p>
<p>blockSize：自适应确定阈值的像素领域大小，一般为3、5、7的级数</p>
<p>C：从平均值或者加权平均值中减去的常数，可以为正，也可以为负</p>
<p>该函数将灰度图像转换成二值图像，通过均值法和高斯法自适应地计算blockSize*blockSize领域内的阈值，之后进行二值化。</p>
<p>示例程序：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;opencv2\opencv.hpp&gt;</span>  <span class="comment">//加载OpenCV4的头文件</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;vector&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> cv; <span class="comment">//OpenCV命名空间</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	Mat img = imread(<span class="string">&quot;lena.jpg&quot;</span>);</span><br><span class="line">	<span class="keyword">if</span> (img.empty())</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;请确认图像文件名称是否正确&quot;</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	Mat gray;</span><br><span class="line">	cvtColor(img, gray, COLOR_BGR2GRAY);</span><br><span class="line">	Mat img_B, img_B_V, gray_B, gray_B_V, gray_T, gray_T_V, gray_TRUNC;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//彩色图像二值化</span></span><br><span class="line">	threshold(img, img_B, <span class="number">125</span>, <span class="number">255</span>, THRESH_BINARY);</span><br><span class="line">	threshold(img, img_B_V, <span class="number">125</span>, <span class="number">255</span>, THRESH_BINARY_INV);</span><br><span class="line">	imshow(<span class="string">&quot;img_B&quot;</span>, img_B);</span><br><span class="line">	imshow(<span class="string">&quot;img_B_V&quot;</span>, img_B);</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//灰度图BINARY二值化</span></span><br><span class="line">	threshold(gray, gray_B, <span class="number">125</span>, <span class="number">255</span>, THRESH_BINARY);</span><br><span class="line">	threshold(gray, gray_B_V, <span class="number">125</span>, <span class="number">255</span>, THRESH_BINARY_INV);</span><br><span class="line">	imshow(<span class="string">&quot;gray_B&quot;</span>,gray_B);</span><br><span class="line">	imshow(<span class="string">&quot;gray_B_V&quot;</span>, gray_B_V);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//灰度图像TOZERO变换</span></span><br><span class="line">	threshold(gray, gray_T, <span class="number">125</span>, <span class="number">255</span>, THRESH_TOZERO);</span><br><span class="line">	threshold(gray, gray_T_V, <span class="number">125</span>, <span class="number">255</span>, THRESH_TOZERO_INV);</span><br><span class="line">	imshow(<span class="string">&quot;gray_T&quot;</span>, gray_T);</span><br><span class="line">	imshow(<span class="string">&quot;gray_T_V&quot;</span>, gray_T_V);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//灰度图像TRUNC变换</span></span><br><span class="line">	threshold(gray, gray_TRUNC, <span class="number">125</span>, <span class="number">255</span>, THRESH_TRUNC);</span><br><span class="line">	imshow(<span class="string">&quot;gray_TRUNC&quot;</span>, gray_TRUNC);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//灰度图像大律法和三角形法二值化</span></span><br><span class="line">	Mat img_Thr = imread(<span class="string">&quot;threshold.png&quot;</span>, IMREAD_GRAYSCALE); <span class="comment">//将图像转换成单通道灰度图像</span></span><br><span class="line">	Mat img_Thr_O, img_Thr_T;</span><br><span class="line">	threshold(img_Thr, img_Thr_O, <span class="number">100</span>, <span class="number">255</span>, THRESH_BINARY | THRESH_OTSU);  <span class="comment">//大律法</span></span><br><span class="line">	threshold(img_Thr, img_Thr_T, <span class="number">125</span>, <span class="number">255</span>, THRESH_BINARY | THRESH_TRIANGLE);  <span class="comment">//三角形法</span></span><br><span class="line">	imshow(<span class="string">&quot;img_Thr&quot;</span>, img_Thr);</span><br><span class="line">	imshow(<span class="string">&quot;img_Thr_O&quot;</span>, img_Thr_O);</span><br><span class="line">	imshow(<span class="string">&quot;img_Thr_T&quot;</span>, img_Thr_T);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//灰度图像自适应二值化</span></span><br><span class="line">	Mat adaptive_mean, adaptive_gauss;</span><br><span class="line">	adaptiveThreshold(img_Thr, adaptive_mean, <span class="number">255</span>, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, <span class="number">55</span>, <span class="number">0</span>);</span><br><span class="line">	adaptiveThreshold(img_Thr, adaptive_gauss, <span class="number">255</span>, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, <span class="number">55</span>, <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">	imshow(<span class="string">&quot;adaptive_mean&quot;</span>, adaptive_mean);</span><br><span class="line">	imshow(<span class="string">&quot;adaptive_gauss&quot;</span>, adaptive_gauss);</span><br><span class="line">	waitKey(<span class="number">0</span>);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;  <span class="comment">//程序结束</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>img_B:</p>
<img src="https://img-blog.csdnimg.cn/32acfdefbdc842e7b011b626d20d9727.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" width="40%">

<p>img_B_V:</p>
<img src="https://img-blog.csdnimg.cn/568482d79b2542099d8257b3047791c9.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" width="40%">

<p>可以看出差别不是很大</p>
<p>gray_TRUNC:</p>
<img src="https://img-blog.csdnimg.cn/d561bc8c8a2446c7a9c3a5213885f569.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" width="40%">

<p>gray_T_V:</p>
<img src="https://img-blog.csdnimg.cn/c5387486452b44168cbcec6e32f77209.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" width="40%">

<p>gray_T:</p>
<img src="https://img-blog.csdnimg.cn/02fb90b0437f4823a63377138bab8b9c.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" width="40%">

<p>gray_B_V:</p>
<img src="https://img-blog.csdnimg.cn/97e316a7fcbc4e21807102dca1b3bec1.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" width="40%">

<p>gray_B:</p>
<img src="https://img-blog.csdnimg.cn/be0f6d5fc9954132a650cfb55b91c03a.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" width="40%">

<p>原图img_Thr:</p>
<img src="https://img-blog.csdnimg.cn/dd0a2f4d54694c14a1f8a14de69c066f.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" width="40%">

<p>大律法img_Thr_O:</p>
<img src="https://img-blog.csdnimg.cn/ec3c729497fe40e8b1b2bd3724c34a3f.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" width="40%">

<p>三角形法img_Thr_T:</p>
<img src="https://img-blog.csdnimg.cn/c4177336af3f4f13b4fa6f835fd42ef1.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" width="40%">

<p>均值法adaptiv_mean:</p>
<img src="https://img-blog.csdnimg.cn/044a064b0fff4dc8beba31a48c34a3b5.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" width="40%">

<p>高斯法adaptive_gauss:</p>
<img src="https://img-blog.csdnimg.cn/c5e772d0ab8e4fc098e0eb2c6521fbaa.png?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIwMTc3MzI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" width="40%">



<p>感谢阅读！</p>
<p>也欢迎大家关注小白博主，多多鼓励一下！ </p>

    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>杨大熊
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://yang-da-xiong.gitee.io/2022/02/13/opencv%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%E4%B9%8B%E5%9B%BE%E5%83%8F%E6%9C%80%E5%80%BC%E4%B8%8E%E4%BA%8C%E5%80%BC%E5%8C%96/" title="opencv学习笔记之图像最值与二值化">https://yang-da-xiong.gitee.io/2022/02/13/opencv学习笔记之图像最值与二值化/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/c/" rel="tag"># c++</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2022/02/12/%E7%AE%97%E6%B3%95%E7%BB%83%E4%B9%A0%E9%A2%9829---%E8%93%9D%E6%A1%A5%E6%9D%AF2021%E7%9C%81%E8%B5%9B%E2%80%9C%E6%97%B6%E9%97%B4%E6%98%BE%E7%A4%BA%E2%80%9D/" rel="prev" title="算法练习题29---蓝桥杯2021省赛“时间显示”">
      <i class="fa fa-chevron-left"></i> 算法练习题29---蓝桥杯2021省赛“时间显示”
    </a></div>
      <div class="post-nav-item">
    <a href="/2022/02/14/opencv%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%E4%B9%8B%E5%9B%BE%E5%83%8F%E5%8F%98%E6%8D%A2/" rel="next" title="opencv学习笔记之图像变换">
      opencv学习笔记之图像变换 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E5%9B%BE%E5%83%8F%E6%9C%80%E5%A4%A7%E5%80%BC%E4%B8%8E%E6%9C%80%E5%B0%8F%E5%80%BC%E7%BB%9F%E8%AE%A1"><span class="nav-number">2.</span> <span class="nav-text">一、图像最大值与最小值统计</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E5%9B%BE%E5%83%8F%E4%BA%8C%E5%80%BC%E5%8C%96"><span class="nav-number">3.</span> <span class="nav-text">二、图像二值化</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#threshold-%E5%87%BD%E6%95%B0"><span class="nav-number">3.0.0.1.</span> <span class="nav-text">threshold()函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#adaptiveThreshold-%E5%87%BD%E6%95%B0"><span class="nav-number">3.0.0.2.</span> <span class="nav-text">adaptiveThreshold()函数</span></a></li></ol></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="杨大熊"
      src="/images/avatar.png">
  <p class="site-author-name" itemprop="name">杨大熊</p>
  <div class="site-description" itemprop="description">各类IT知识分享</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">58</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/Yang-Da-xiong?tab=repositories" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Yang-Da-xiong?tab&#x3D;repositories" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/weixin_45775703?spm=1000.2115.3001.5343" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;weixin_45775703?spm&#x3D;1000.2115.3001.5343" rel="noopener" target="_blank"><i class="fab fa-codiepie fa-fw"></i>CSDN</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨大熊</span>
</div>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>

<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>

<div class="theme-info">
<div class="powered-by"></div>
<span class="post-count">博客全站共56.5k字</span>
</div>
        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"model":{"jsonPath":"/live2dw/assets/wanko.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"log":false});</script></body>
</html>

<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/schemes/clicklove.js"></script>
